var _ = require('lodash'),
    Q = require('q'),
    mongoose = require('mongoose'),
    workLocationController = require('../../../CBO/server/controllers/WorkLocation.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    stationTerminalController = require('../../../Initialize/server/controllers/StationTerminal.server.controller'),
    stationWorkController = require('../../../Initialize/server/controllers/StationWork.server.controller');

exports.getStation = function(req, res) {
    workLocationController.getStation().then(function (records) {
        res.json({
            Data: records,
            Error: null
        });
    }, function (err) {
        res.json({
            Data: null,
            Error: err
        });
    });
};

exports.getDepartmentStation = function(req, res) {
    workLocationController.getDepartmentStation().then(function (records) {
        return populateDepartment(records);
    }).then(function (records) {
        res.json({
            Data: records,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

exports.registerTerminal = function (req, res) {
    var parameter = req.body.Parameter,
        workLocationId = parameter.WorkLocationID,
        terminalUniqueId = parameter.TerminalUniqueID,
        terminalType = parameter.TerminalType;

    queryTerminalId(terminalUniqueId, terminalType).then(function (terminalId) {
        return bindStation(terminalId, workLocationId);
    }).then(function () {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

exports.getLastRegister = function(req, res) {
    var parameter = req.body.Parameter,
        terminalUniqueId = parameter.TerminalUniqueID;

    var registerInfo = {};
    terminalController.findByUniqueID(terminalUniqueId, function (err, terminalRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (terminalRecord === null) {
            res.json({
                Data: registerInfo,
                Error: null
            });
            return;
        }
        _.merge(registerInfo, {
            Terminal: {
                _id: terminalRecord._id,
                Code: terminalRecord.Code,
                Name: terminalRecord.Name
            }
        });
        stationTerminalController.findByTerminalID(terminalRecord._id, function (err, record) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
                return;
            }
            if (record === null || !record.WorkLocation) {
                res.json({
                    Data: registerInfo,
                    Error: null
                });
                return;
            }
            _.merge(registerInfo, {
                WorkLocation: {
                    _id: record.WorkLocation._id,
                    Code: record.WorkLocation.Code,
                    Name: record.WorkLocation.Name,
                    ModifyOn: record.ModifyOn
                }
            });
            if (record.WorkLocation.Department) {
                _.merge(registerInfo, {
                Department: {
                    _id: record.WorkLocation.Department._id,
                    Code: record.WorkLocation.Department.Code,
                    Name: record.WorkLocation.Department.Name
                }
            });
            }
            stationWorkController.findByWorkLocationID(record.WorkLocation._id, function (err, stationWorkRecords) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                if (stationWorkRecords === null || stationWorkRecords.length === 0 || !stationWorkRecords[0].Work) {
                    res.json({
                        Data: registerInfo,
                        Error: null
                    });
                    return;
                }
                _.merge(registerInfo, {
                    Work: {
                        _id: stationWorkRecords[0].Work._id,
                        Code: stationWorkRecords[0].Work.Code,
                        Name: stationWorkRecords[0].Work.Name
                    }
                });
                res.json({
                    Data: registerInfo,
                    Error: null
                });
            });
        });
    });   
};

function populateDepartment (records) {
    var deferred = Q.defer();

    var departmentModel = mongoose.model('Department');
    departmentModel.populate(records, {path: 'Department', select: 'Code Name'}, function (err, results) {
        if (err) {
            deferred.reject(err);
            return
        }
        deferred.resolve(results);
    });

    return deferred.promise;
}

function queryTerminalId (terminalUniqueId, terminalType) {
    var deferred = Q.defer();

    terminalController.findByUniqueID(terminalUniqueId, function (err, terminalRecord) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (terminalRecord) {
            deferred.resolve(terminalRecord._id);
            return;
        }
        var record = {
            Code: terminalUniqueId,
            Name: '终端' + terminalUniqueId,
            UniqueID: terminalUniqueId,
            Type: terminalType || 0,
            IsEffective: true
        };
        terminalController.insert(record, function (err, newRecord) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(newRecord._id);
        });
    });

    return deferred.promise;
}

function bindStation (terminalId, workLocationId) {
    var deferred = Q.defer();

    stationTerminalController.findOne(terminalId).then(function (record) {
        if (record) {
            return stationTerminalController.update({
                _id: record._id,
                WorkLocation: workLocationId,
                SysVersion: record.SysVersion
            });
        } else {
            return stationTerminalController.insert({
                Terminal: terminalId,
                WorkLocation: workLocationId
            });
        }
    }).then(function () {
        deferred.resolve();
    }).catch(function (err) {
        deferred.reject(err);
    })
    .done();

    return deferred.promise;
}
